package exit.manboking.widget;


import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import exit.manboking.common.Code;
import exit.manboking.main.R;
import exit.manboking.service.values;

public class MyWidget extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		// TODO Auto-generated method stub
		onWidgetUpdate(context, appWidgetManager, appWidgetIds);
	}
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		super.onReceive(context, intent);
		if(intent.getAction().equals(Code.BROADCAST_SENSOR) || intent.getAction().equals(Code.CLICK_ACTION) ){
			updateWi(context);
		}
	}

	public void onWidgetUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		
		for (int i = 0; i < appWidgetIds.length; i++) {
			int           ids           = appWidgetIds[i];
			RemoteViews   views         = new RemoteViews(context.getPackageName(), R.layout.widget);
			Intent        intent        = new Intent(Code.CLICK_ACTION);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			views.setTextViewText( R.id.widget_text_step,                 String.valueOf(values.getValues().getStep()));
			views.setTextViewText( R.id.widget_text_calorie,              values.getValues().getCalorie());
			views.setProgressBar(  R.id.widget_progressbar,               values.getValues().getGoalStep(), values.getValues().getStep(), false);
			views.setTextViewText( R.id.widget_text_progress_percentage,  "" + values.getValues().getGoalSuccessRate() + "%");
			views.setOnClickPendingIntent(R.id.widget_toggleBtn,          pendingIntent);
			
			appWidgetManager.updateAppWidget(ids,views);
		}
	}

	public void updateWi(Context context) {
		ComponentName    componentName = new ComponentName(context, MyWidget.class);
		AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
		int[]            apid         = widgetManager.getAppWidgetIds(componentName);
		onWidgetUpdate(context,widgetManager,apid);
	}



}
